/**
 * UninaDocentiSync - A Java application to synchronize Unina resources
 * Copyright (C) 2011  Fabio Scippacercola (nonplay.programmer@gmail.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * MainFrame.java
 *
 * Created on Oct 22, 2011, 4:15:37 PM
 */

package uninadocentisync.guibeans;

import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import uninadocenti.framework.Insegnamento;
import uninadocentisync.ApplicationUtils;

/**
 *
 * @author user
 */
public class MainFrame extends javax.swing.JFrame {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jFileChooser1 = new javax.swing.JFileChooser();
        uninaDocentiSyncAppBean1 = (UninaDocentiSyncAppBean)ApplicationUtils.getInstance().lookAndStore("uninaDocentiSyncAppBean", new UninaDocentiSyncAppBean());
        headLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        insTable = new javax.swing.JTable();
        addInsButton = new javax.swing.JButton();
        delInsButton = new javax.swing.JButton();
        selAllButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        fileFolderTextBox = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        loginButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        syncButton = new javax.swing.JButton();
        overwriteCheckbox = new javax.swing.JCheckBox();

        jFileChooser1.setDialogTitle("Scegli una cartella destinazione...");
        jFileChooser1.setFileFilter(null);
        jFileChooser1.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("UninaDocentiSync");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        headLabel.setBackground(new java.awt.Color(255, 255, 255));
        headLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uninadocentisync/gui/res/UninaDocentiSync.png"))); // NOI18N
        headLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(138, 138, 138)));
        headLabel.setOpaque(true);

        jLabel2.setText("Corsi sottoposti ad aggiornamento:");

        insTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${insegnamentiRegistrati}");
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, uninaDocentiSyncAppBean1, eLProperty, insTable, "InsegnamentiTableBinding"); // NOI18N
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${docenteInsegnamento}"));
        columnBinding.setColumnName("Docente Insegnamento");
        columnBinding.setColumnClass(uninadocenti.framework.Docente.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nomeInsegnamento}"));
        columnBinding.setColumnName("Nome Insegnamento");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(insTable);

        addInsButton.setText("Aggiungi...");
        addInsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addInsButtonActionPerformed(evt);
            }
        });

        delInsButton.setText("Rimuovi");
        delInsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delInsButtonActionPerformed(evt);
            }
        });

        selAllButton.setText("Seleziona tutto");
        selAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selAllButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Cartella di destinazione:");

        fileFolderTextBox.setEditable(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, uninaDocentiSyncAppBean1, org.jdesktop.beansbinding.ELProperty.create("${fileFolder}"), fileFolderTextBox, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setConverter(new org.jdesktop.beansbinding.Converter<java.io.File, String>() {
            @Override
            public String convertForward(java.io.File f) {
                try {
                    return f.getCanonicalPath();
                }
                catch (IOException e) {
                    return e.getMessage();
                }
            }

            public java.io.File convertReverse(String s) {
                return new java.io.File(s);
            }
        }
    );
    bindingGroup.addBinding(binding);

    browseButton.setText("Sfoglia...");
    browseButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            browseButtonActionPerformed(evt);
        }
    });

    jLabel3.setText("File Duplicati:");

    loginButton.setText("Login");
    loginButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            loginButtonActionPerformed(evt);
        }
    });

    exitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uninadocentisync/gui/res/System-log-out-2.png"))); // NOI18N
    exitButton.setText("Esci");
    exitButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            exitButtonActionPerformed(evt);
        }
    });

    syncButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/uninadocentisync/gui/res/update.png"))); // NOI18N
    syncButton.setText("Sincronizza...");
    syncButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            syncButtonActionPerformed(evt);
        }
    });

    overwriteCheckbox.setText("Sovrascrivi");

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, uninaDocentiSyncAppBean1, org.jdesktop.beansbinding.ELProperty.create("${overwriteFiles}"), overwriteCheckbox, org.jdesktop.beansbinding.BeanProperty.create("selected"));
    bindingGroup.addBinding(binding);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                .addComponent(headLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(addInsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(delInsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(selAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(exitButton, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(syncButton, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(fileFolderTextBox, javax.swing.GroupLayout.DEFAULT_SIZE, 459, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(overwriteCheckbox)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(loginButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(browseButton, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))))
                    .addGap(2, 2, 2)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(headLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel2)
            .addGap(3, 3, 3)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(addInsButton)
                .addComponent(delInsButton)
                .addComponent(selAllButton))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(fileFolderTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(browseButton))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(loginButton)
                .addComponent(overwriteCheckbox))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(exitButton)
                .addComponent(syncButton))
            .addContainerGap())
    );

    bindingGroup.bind();

    pack();
    }// </editor-fold>//GEN-END:initComponents

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        int returnVal = jFileChooser1.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            final File file = jFileChooser1.getSelectedFile();
            uninaDocentiSyncAppBean1.setFileFolder(file);
        }
    }//GEN-LAST:event_browseButtonActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
         dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }//GEN-LAST:event_exitButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (JOptionPane.showConfirmDialog(this, "Sei sicuro di voler uscire?", "Uscire?", JOptionPane.YES_NO_OPTION)
                == JOptionPane.YES_OPTION)
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        else
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }//GEN-LAST:event_formWindowClosing

    private void addInsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addInsButtonActionPerformed
        if (!uninaDocentiSyncAppBean1.isLoginSetted())
            loginButtonActionPerformed(evt);

        if (uninaDocentiSyncAppBean1.isLoginSetted())
        {
            Insegnamento i = UninaSelecter.getInsegnamento(this, uninaDocentiSyncAppBean1.getWebDocenti());
            if (i != null) uninaDocentiSyncAppBean1.doAddInsegnamento(i);
        }
    }//GEN-LAST:event_addInsButtonActionPerformed

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        try {
            LoginDialog.LoginInfo l = LoginDialog.showLoginDialog();
            uninaDocentiSyncAppBean1.doLogin(l.getUsername(), l.getPassword());
        } catch (Exception e)
        {
            // TODO Take an action!
        }
    }//GEN-LAST:event_loginButtonActionPerformed

    private void delInsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delInsButtonActionPerformed
        int[] v = insTable.getSelectedRows();
        if (v.length > 0 && JOptionPane.showConfirmDialog(this, "Sei sicuro di voler eliminare gli insegnamenti selezionati?", "Confermi?", JOptionPane.YES_NO_OPTION)
                == JOptionPane.YES_OPTION)
        {
            List<Insegnamento> l = uninaDocentiSyncAppBean1.getInsegnamentiRegistrati();
            for (int i : v) uninaDocentiSyncAppBean1.doRemoveInsegnamento(l.get(i));
        }
    }//GEN-LAST:event_delInsButtonActionPerformed

    private void selAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selAllButtonActionPerformed
        insTable.selectAll();
    }//GEN-LAST:event_selAllButtonActionPerformed

    private void syncButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_syncButtonActionPerformed
        if (!uninaDocentiSyncAppBean1.isLoginSetted())
            loginButtonActionPerformed(evt);
        if (uninaDocentiSyncAppBean1.getFileFolder() == null)
            browseButtonActionPerformed(evt);

        if (uninaDocentiSyncAppBean1.isLoginSetted() && uninaDocentiSyncAppBean1.getFileFolder() != null) {
            int[] selectedIns = this.insTable.getSelectedRows();
            if (selectedIns.length > 0)
            {
                Insegnamento[] selInsegnamenti = new Insegnamento[selectedIns.length];
                for (int i = 0; i < selectedIns.length; i++)
                    selInsegnamenti[i] = uninaDocentiSyncAppBean1.getInsegnamentiRegistrati().get(selectedIns[i]);

                uninadocentisync.guibeans.UpdatingDialog d = new uninadocentisync.guibeans.UpdatingDialog(uninaDocentiSyncAppBean1, selInsegnamenti);
                d.setModal(true);
                d.setVisible(true);
            }
            else
                JOptionPane.showMessageDialog(this, "Seleziona almeno un insegnamento per la sincronizzazione...", "Attenzione!", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_syncButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addInsButton;
    private javax.swing.JButton browseButton;
    private javax.swing.JButton delInsButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JTextField fileFolderTextBox;
    private javax.swing.JLabel headLabel;
    private javax.swing.JTable insTable;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton loginButton;
    private javax.swing.JCheckBox overwriteCheckbox;
    private javax.swing.JButton selAllButton;
    private javax.swing.JButton syncButton;
    private uninadocentisync.guibeans.UninaDocentiSyncAppBean uninaDocentiSyncAppBean1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
